package com.jijs.framework.interceptors;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.jijs.framework.model.pmodel.AdeUser;
import com.jijs.framework.service.ModuleManagerService;
import com.jijs.framework.util.StringUtil;
import com.jijs.framework.util.UserUtil;

/**
 * 权限拦截器
 * 
 * @author jijs
 * 
 */
public class SecurityInterceptor implements HandlerInterceptor {

	/** 日志对象 */
	private static final Logger LOG = Logger.getLogger(SecurityInterceptor.class);

	/** 模块服务类 */
	@Autowired
	private ModuleManagerService moduleService;

	/** 不需要拦截的资源 */
	private List<String> excludeUrls;

	/**
	 * 需要验证权限的资源前缀<br>
	 * 请注意：该路径应该以"/"开始 ，并且以"/"结束
	 */
	private List<String> roleInterceptorUrlPrefixs;

	public void setRoleInterceptorUrlPrefixs(List<String> interceptorUrlPrefixs) {
		this.roleInterceptorUrlPrefixs = interceptorUrlPrefixs;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

	/**
	 * 在调用controller具体方法前拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {

		String requestUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		String url = requestUri.substring(contextPath.length());

		AdeUser user = UserUtil.getLoginUser(request);

		// 判断是否需要权限过滤的地址
		if (roleInterceptorUrlPrefixs !=null && !StringUtil.startWith(url, roleInterceptorUrlPrefixs)) {
			return true;
		}

		// 不需要权限验证的地址
		if (excludeUrls.indexOf(url) != -1) {
			return true;
		}

		if (user == null) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("当前用户未登录，请求的地址不在未登录可访问地址列表中。地址:" + url);
			}
			request.setAttribute("message", "请登录系统后，再进行操作！");
			request.getRequestDispatcher("/admin/index.jsp").forward(request, response);
			return false;
		}

		// 地址在权限列表中，但是用户没有该权限
		List<String> allPermissions = moduleService.allPermission();
		List<String> userPermissions = user.getModuleList();

		if (allPermissions.contains(url)) {// 访问的地址不再权限列表中
			if (userPermissions.contains(url)) {// 访问的地址在权限列表中，但是当前登录的用户没有权限
				return true;
			} else {
				handleNoSecurity(request, response);
				return false;
			}
		}

		return true;
	}

	/**
	 * 跳转到没有权限页面
	 * 
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	protected void handleNoSecurity(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		request.setAttribute("msg", "您没有授权访问该页面");
		request.getRequestDispatcher("/error/noSecurity.jsp").forward(request, response);
	}

	/**
	 * 完成页面的render后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
			Exception exception) throws Exception {

	}

	/**
	 * 在调用controller具体方法后拦截
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
			ModelAndView modelAndView) throws Exception {

	}
}
